﻿using OpenTK.Graphics.OpenGL;
using OpenTK.Mathematics;

namespace OpenGl.Explore.FirstApp
{
    public unsafe class OpenglGraphics
    {
        private Matrix4 _baseMatrix = Matrix4.Identity;
        private ShaderProgram _program;
        private Triangle _triangle;
        private VertexArray _va;

        private VertexBuffer _vb;
        public OpenglGraphics()
        {
        }

        public void MoveDown()
        {
            _triangle.Transform.SetTranslation(new Vector3(0, -3f, 0));
        }

        public void MoveLeft()
        {
            _triangle.Transform.SetTranslation(new Vector3(-3f, 0, 0));
        }

        public void MoveRight()
        {
            _triangle.Transform.SetTranslation(new Vector3(3f, 0, 0));
        }

        public void MoveUp()
        {
            _triangle.Transform.SetTranslation(new Vector3(0, 3f, 0));
        }

        public void Render()
        {
            GL.Clear(ClearBufferMask.ColorBufferBit);
            GL.ClearColor(0, 0, 0, 1);
            _program.SetUniform("transform", _triangle.Transform.TransformMatrix * _baseMatrix);
            GL.DrawArrays(PrimitiveType.Triangles, 0, 3);
        }

        public void SetMatrix(Matrix4 matrix4)
        {
            _baseMatrix = matrix4;
        }

        public void SetupVertices()
        {
            _triangle = new Triangle()
            {
                V1 = new Vertex() { Position = new Vector2(0f, 10f), Color = new Vector3(1f, 0f, 0f) },
                V2 = new Vertex() { Position = new Vector2(-10f, -10f), Color = new Vector3(0f, 1f, 0f) },
                V3 = new Vertex() { Position = new Vector2(10f, -10f), Color = new Vector3(0f, 0f, 1f) }
            };

            _va = new VertexArray();
            _va.Bind();


            _vb = new VertexBuffer();
            _vb.Bind();
            _vb.SetData<Vertex>(_triangle.Vertices, sizeof(Vertex), BufferUsageHint.StaticDraw, new int[] { 2, 3 });


            _program = new ShaderProgram();
            using (VertexShader vs = new VertexShader(AppDomain.CurrentDomain.BaseDirectory + "Shaders\\shader.vert"))
            {

                using (FragmentShader fs = new FragmentShader(AppDomain.CurrentDomain.BaseDirectory + "Shaders\\shader.frag"))
                {
                    _program.Attach(vs);
                    _program.Attach(fs);
                    _program.Link();
                }
            }
            _program.Bind();
        }
    }
}